package com.LeeCode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 字母与数字
 */

public class Code面试题17_05 {
    public static void main(String[] args) {

    }

    public String[] findLongestSubarray(String[] array) {
        int start = 0, maxLen = 0, preSum = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        for (int i = 0; i < array.length; i++) {
            int add = isDigit(array[i]) ? 1 : -1;
            preSum += add;
            if (map.containsKey(preSum)) {
                int length = i - map.get(preSum);
                if (length > maxLen) {
                    maxLen = length;
                    start = i - length + 1;
                }
            } else {
                map.put(preSum, i);
            }
        }
        if (maxLen == 0) return new String[]{};
        return Arrays.copyOfRange(array, start, start + maxLen);
    }

    private boolean isDigit(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }

        try {
            int num = Integer.parseInt(str);
            return num >= 0;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}
